package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.RoleQuery;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("list")
    @RequiredPermission(name = "角色列表",expression ="role:list")
    public String list(Model model, RoleQuery qo){
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "/role/list";
    }

    @RequestMapping("input")
    @RequiredPermission(name = "角色编辑",expression ="role:input")
    public String input(Long id,Model model){
        if (id != null){
            Role role = roleService.get(id);
            model.addAttribute("role",role);
        }
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions",permissions);
        return "/role/input";
    }

    @RequestMapping("saveOrUpdate")
    @RequiredPermission(name = "角色更新和保存",expression ="role:saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Role role, Long[] ids){
        try {
            if (role.getId() != null){
                roleService.update(role,ids);
            }
            else {
                roleService.insert(role,ids);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"角色保存失败,请联系管理员");
        }
    }

    @RequestMapping("delete")
    @RequiredPermission(name = "角色删除",expression ="role:delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            if (id != null){
                roleService.delete(id);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"角色删除失败,请联系管理员");
        }
    }
}
